import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:ecy_app_flutter/ecycommon/EcyCommonWidgets.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';

import '../../EcyRouter.dart';
import '../../constant/EcyEventConsnt.dart';
import '../../ecycommon/EcyAPI.dart';
import '../../ecycommon/EcyEventBus.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../ecycommon/utils/EcyLogger.dart';
import '../../ecycommon/utils/EcyStorage.dart';
import '../../ecycommon/utils/EcyUserUtil.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../../user/model/EcyUserModel.dart';
import '../login/common/DateUtil.dart';
import '../login/common/ProfileBirthdayPicker.dart';

class EcyPersonInfoPage extends EcyCommonBaseWidget {
  EcyPersonInfoPage({required super.key});

  @override
  _EcyPersonInfoPageState createState() {
    return _EcyPersonInfoPageState();
  }
}

class _EcyPersonInfoPageState extends EcyCommonBaseWidgetState {
  final _formKey = GlobalKey<FormState>();
  final _nicknameController = TextEditingController();
  final _signatureController = TextEditingController();
  final _selectedGenderController = TextEditingController();
  final _birthdayController = TextEditingController();

  List<String> genderList = ["男", "女", "其他"];
  int _selectedGender = 0;
  late int? _selectedGenderIndex;
  String _birthday = "";
  String avatarUrl = "";
  //头像
  Widget avatar = Image.asset('assets/images/profile.png', width: 120);
  //相机图标
  Widget camera = Image.asset('assets/images/camera2.png', width: 38);

  final ImagePicker _picker = ImagePicker();

  Future<void> _pickImage() async {
    try {
      final pickedFile =
      await _picker.pickImage(source: ImageSource.gallery); // 从相册选择图片
      // final pickedFile = await _picker.pickImage(source: ImageSource.camera); // 从相机选择图片

      // TODO 裁剪
      if (pickedFile != null) {
        final croppedFile = await ImageCropper().cropImage(
          sourcePath: pickedFile.path,
          compressFormat: ImageCompressFormat.jpg,
          compressQuality: 85, // 压缩质量 (0-100)
          aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
          uiSettings: [
            AndroidUiSettings(
              toolbarTitle: '图片裁剪',
              toolbarColor: const Color(0XFFEA4B9B),
              statusBarColor: const Color(0XFFEA4B9B),
              activeControlsWidgetColor: const Color(0XFFEA4B9B),
              toolbarWidgetColor: Colors.white,
              cropFrameColor: Colors.transparent,
              showCropGrid: false,
              cropStyle: CropStyle.circle,
              initAspectRatio: CropAspectRatioPreset.square,
              lockAspectRatio: true,
            ),
            IOSUiSettings(
              title: '图片裁剪',
              doneButtonTitle: '完成',
              cancelButtonTitle: '取消',
              aspectRatioLockEnabled: true,
            ),
          ],
        );

        if (croppedFile != null) {
          // 后端接收文件的参数名为 file
          FormData formData = FormData.fromMap({
            "file": await MultipartFile.fromFile(
              croppedFile.path,
            ),
          });
          var response = await EcyRequestbasemanager()
              .post("/app/api/app/user/avatar", formData);
          if (response != null) {
            setState(() {
              avatarUrl = response["data"];
            });
            EcyStorage.getString(EcyUserUtil.kLoginedUserInfo).then((value) {
              if (value != null) {
                EcyUserModel userModel = EcyUserModel.fromJson(json.decode(value));
                userModel.avatar = response["data"];
                EcyStorage.setString(
                    EcyUserUtil.kLoginedUserInfo, json.encode(userModel));
                //发送全局通知
                EcyEventBus().emit(EcyEventConst.kEditUser);
              }
            });
          }
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }


  @override
  void initState() {
    super.initState();

    EcyStorage.getString(EcyUserUtil.kLoginedUserInfo).then((value) {
      if (value != null) {
        EcyUserModel userModel = EcyUserModel.fromJson(json.decode(value));
        setState(() {
          _nicknameController.text = userModel.nickname ?? "";
          _signatureController.text = userModel.signature ?? "";
          _selectedGenderController.text =
              userModel.gender != null ? genderList[userModel.gender!] : "";
          _selectedGenderIndex = userModel.gender;
          _selectedGender = _selectedGenderIndex ?? 0;
          _birthdayController.text = userModel.birthday ?? "";
          avatarUrl = userModel.avatar ?? '';
        });
      }
    });
  }

  void saveUserModel() async {
    try {
      Map<String, dynamic> body = {
        "nickname": _nicknameController.text,
        "signature": _signatureController.text,
        "gender": _selectedGenderIndex, // 0 男 1 女 2 其他
        "birthday": _birthdayController.text.isNotEmpty
            ? "${_birthdayController.text} 00:00:00"
            : "",
      };
      var response =
          await EcyRequestbasemanager().put(EcyAPI.saveAppUser.url, body);
      if (response != null) {
        //模型自动解析
        var resp = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (resp != null) {
          if (resp.code == 0 || resp.code == 200) {
            EcyStorage.getString(EcyUserUtil.kLoginedUserInfo).then((value) {
              if (value != null) {
                EcyUserModel userModel =
                    EcyUserModel.fromJson(json.decode(value));
                if (response['data'] != null) {
                  userModel.nickname = response['data']["nickname"];
                  userModel.signature = response['data']["signature"];
                  _nicknameController.text = userModel.nickname??"";
                  _signatureController.text = userModel.signature??"";
                } else {
                  userModel.nickname = _nicknameController.text;
                  userModel.signature = _signatureController.text;
                }
                userModel.gender = _selectedGenderIndex;
                userModel.birthday = _birthdayController.text;
                EcyStorage.setString(
                    EcyUserUtil.kLoginedUserInfo, json.encode(userModel));

                //发送全局通知
                EcyEventBus().emit(EcyEventConst.kEditUser);
              }
            });
            EasyLoading.showToast(resp.msg ?? "保存成功",
                duration: const Duration(seconds: 1));
          } else {
            EasyLoading.showToast(resp.msg ?? "请稍后再试",
                duration: const Duration(seconds: 1));
          }
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 1));
      EcyLogger.log(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        child: KeyboardDismisser(
            gestures: const [
              GestureType.onTap,
              GestureType.onPanUpdateDownDirection
            ],
            child: Scaffold(
              resizeToAvoidBottomInset: false,
              backgroundColor: const Color(0XFFF5F5F5),
              appBar: AppBar(
                backgroundColor: const Color(0xFFFFFFFF),
                title: Text(
                  "个人资料",
                  style: TextStyle(
                      fontFamily: "PingFang SC",
                      fontWeight: FontWeight.w700,
                      fontSize: 16.sp,
                      color: const Color(0xFF262626)),
                ),
                centerTitle: true,
                actions: [
                  TextButton(
                      style: TextButton.styleFrom(
                          foregroundColor: const Color(0XFFEA4B9B)),
                      onPressed: () {
                        FocusScope.of(context).requestFocus(FocusNode());
                        saveUserModel();
                      },
                      child: const Text("保存"))
                ],
              ),
              body: Container(
                color: const Color(0XFFF5F5F5),
                child: Form(
                    key: _formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                            width: double.infinity,
                            height: 100.h,
                            color: const Color(0xFFFFFFFF),
                            child: Stack(
                              children: [
                                Align(
                                  alignment: Alignment.centerLeft,
                                  child: Padding(
                                    padding: const EdgeInsets.only(
                                        left: 15, top: 10, bottom: 10),
                                    child: SizedBox(
                                      width: 75.w,
                                      height: 75.w,
                                      child: ClipOval(
                                          child: CachedNetworkImage(
                                        width: 70.w,
                                        height: 70.w,
                                        imageUrl: avatarUrl,
                                        imageBuilder:
                                            (context, imageProvider) =>
                                                Container(
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(36.r)),
                                              image: DecorationImage(
                                                  image: imageProvider,
                                                  fit: BoxFit.cover)),
                                        ),
                                        placeholder: (context, url) => avatar,
                                        errorWidget: (context, url, error) =>
                                            avatar,
                                      )),
                                    ),
                                  ),
                                ),
                                Positioned(
                                    top: 65,
                                    left: 70,
                                    child: GestureDetector(
                                      child: ClipOval(
                                        child: Container(
                                            color: const Color(0xFF262626)
                                                .withOpacity(0.8),
                                            width: 24,
                                            height: 24,
                                            child: Padding(
                                                padding: const EdgeInsets.only(
                                                    left: 3,
                                                    right: 3,
                                                    top: 3,
                                                    bottom: 3),
                                                child: camera)),
                                      ),
                                      onTap: () {
                                        _pickImage();
                                      },
                                    )),
                              ],
                            )),
                        const Divider(height: 0, color: Color(0XFFF5F5F5)),
                        Container(
                          width: double.infinity,
                          color: const Color(0xFFFFFFFF),
                          padding: const EdgeInsets.only(top: 5, bottom: 5),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Expanded(
                                flex: 1,
                                child: Padding(
                                    padding: const EdgeInsets.only(left: 15),
                                    child: Text(
                                      '昵称',
                                      style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontSize: 16.sp,
                                        fontWeight: FontWeight.w700,
                                        color: const Color(0xFF262626),
                                      ),
                                    )),
                              ),
                              Expanded(
                                flex: 5,
                                child: TextFormField(
                                  controller: _nicknameController,
                                  decoration: InputDecoration(
                                    hintText: '输入一下昵称吧',
                                    hintFadeDuration: Duration.zero,
                                    border: InputBorder.none,
                                    counterText: '',
                                    hintStyle: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontSize: 16.sp,
                                      fontWeight: FontWeight.w500,
                                      color: const Color(0xFFBFBFBF),
                                    ),
                                  ),
                                  style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w500,
                                    color: const Color(0xFF262626),
                                  ),
                                  maxLength: 11,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const Divider(height: 0, color: Color(0XFFF5F5F5)),
                        Container(
                          width: double.infinity,
                          color: const Color(0xFFFFFFFF),
                          padding: const EdgeInsets.only(top: 5, bottom: 5),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Expanded(
                                flex: 1,
                                child: Padding(
                                    padding: const EdgeInsets.only(left: 15),
                                    child: Text(
                                      '签名',
                                      style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontSize: 16.sp,
                                        fontWeight: FontWeight.w700,
                                        color: const Color(0xFF262626),
                                      ),
                                    )),
                              ),
                              Expanded(
                                flex: 5,
                                child: TextFormField(
                                  controller: _signatureController,
                                  decoration: InputDecoration(
                                    hintText: '介绍一下自己吧',
                                    hintFadeDuration: Duration.zero,
                                    border: InputBorder.none,
                                    hintStyle: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w500,
                                      fontSize: 16.sp,
                                      color: const Color(0xFFBFBFBF),
                                    ),
                                    counterText: '',
                                  ),
                                  style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w500,
                                    color: const Color(0xFF262626),
                                  ),
                                  maxLength: 20,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const Divider(height: 0, color: Color(0XFFF5F5F5)),
                        Container(
                          width: double.infinity,
                          color: const Color(0xFFFFFFFF),
                          padding: const EdgeInsets.only(top: 5, bottom: 5),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Expanded(
                                flex: 1,
                                child: Padding(
                                    padding: const EdgeInsets.only(left: 15),
                                    child: Text(
                                      '性别',
                                      style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontSize: 16.sp,
                                        fontWeight: FontWeight.w700,
                                        color: const Color(0xFF262626),
                                      ),
                                    )),
                              ),
                              Expanded(
                                flex: 5,
                                child: TextFormField(
                                  readOnly: true,
                                  onTap: () {
                                    _showGenderBottomSheet(context);
                                  },
                                  controller: _selectedGenderController,
                                  decoration: const InputDecoration(
                                    hintFadeDuration: Duration.zero,
                                    border: InputBorder.none,
                                    hintText: "请选择",
                                    hintStyle: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w500,
                                      fontSize: 16,
                                      color: Color(0xFFBFBFBF),
                                    ),
                                  ),
                                  style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w500,
                                    color: const Color(0xFF262626),
                                  ),
                                  onSaved: (value) {
                                    FocusScope.of(context).unfocus();
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                        const Divider(height: 0, color: Color(0XFFF5F5F5)),
                        Container(
                          width: double.infinity,
                          color: const Color(0xFFFFFFFF),
                          padding: const EdgeInsets.only(top: 5, bottom: 5),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Expanded(
                                flex: 1,
                                child: Padding(
                                    padding: const EdgeInsets.only(left: 15),
                                    child: Text(
                                      '生日',
                                      style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontSize: 16.sp,
                                        fontWeight: FontWeight.w700,
                                        color: const Color(0xFF262626),
                                      ),
                                    )),
                              ),
                              Expanded(
                                flex: 5,
                                child: TextFormField(
                                  readOnly: true,
                                  onTap: () {
                                    _showbirthdayBottomSheet(context);
                                  },
                                  controller: _birthdayController,
                                  decoration: InputDecoration(
                                    hintFadeDuration: Duration.zero,
                                    hintText: "请选择",
                                    hintStyle: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w500,
                                      fontSize: 16.sp,
                                      color: const Color(0xFFBFBFBF),
                                    ),
                                    border: InputBorder.none,
                                    counterText: '',
                                  ),
                                  style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w500,
                                    color: const Color(0xFF262626),
                                  ),
                                  onSaved: (value) {
                                    FocusScope.of(context).unfocus();
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    )),
              ),
            )));
  }

  // 选择性别
  void _showGenderBottomSheet(BuildContext context) {
    //显示底部弹窗
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      enableDrag: true,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight: Radius.circular(10),
        ),
      ), //圆角
      builder: (context) {
        return Container(
          height: 256.0,
          color: Colors.white,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              _buildButtonRow(context),
              Expanded(
                child: CupertinoPicker(
                  scrollController:
                      FixedExtentScrollController(initialItem: _selectedGender),
                  itemExtent: 32.0, // 每个项目的尺寸
                  children: <Widget>[
                    for (int i = 0; i < genderList.length; i++)
                      Text(genderList[i]),
                  ],
                  onSelectedItemChanged: (int index) {
                    setState(() {
                      _selectedGender = index;
                    });
                  },
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildButtonRow(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        TextButton(
          onPressed: () {
            EcyRouter.pop(context, "");
          },
          child: const Text(
            "取消",
            textAlign: TextAlign.center,
            softWrap: true,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              fontStyle: FontStyle.normal,
              decoration: TextDecoration.none,
            ),
          ),
        ),
        TextButton(
          onPressed: () {
            setState(() {
              _selectedGenderController.text = genderList[_selectedGender];
              _selectedGenderIndex = _selectedGender;
            });
            EcyRouter.pop(context, "");
          },
          child: const Text(
            "确定",
            textAlign: TextAlign.center,
            softWrap: true,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w400,
              fontStyle: FontStyle.normal,
              color: Colors.pink,
              decoration: TextDecoration.none,
            ),
          ),
        ),
      ],
    );
  }

  // 选择生日
  void _showbirthdayBottomSheet(BuildContext context) {
    //显示底部弹窗
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      enableDrag: true,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight: Radius.circular(10),
        ),
      ), //圆角
      builder: (context) {
        return ProfileBirthdayPicker(
          key: const Key("ProfileBirthdayPicker"),
          confirmPressed: (date) {
            _birthday = date.isEmpty
                ? DateUtil.getNowDateTimeFormat(DateUtil.PARAM_FORMAT_1)
                : date;
            setState(() {
              _birthdayController.text = _birthday;
            });
          },
        );
      },
    );
  }
}
